package jee.boot.common.config;

import jee.boot.entity.auth.Account;
import jee.boot.common.properties.ProjectConfig;
import jee.boot.common.standard.AccountHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 默认的账户权限信息获取方式,从缓存中获取
 */
public class DefaultAccountHandlerImpl implements AccountHandler {
    private ProjectConfig projectConfig;

    private Logger logger = LoggerFactory.getLogger(getClass());

    public DefaultAccountHandlerImpl(ProjectConfig projectConfig) {
        this.projectConfig = projectConfig;
    }

    @Override
    public Account getPrincipal() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 认证信息为空,或者还处于UsernamePassword默认(没有完成登录操作)的时候不予返回登录信息
        if (authentication != null && authentication.getPrincipal() instanceof Account) {
            return (Account) authentication.getPrincipal();
        }
        return null;
    }

    /**
     * 是否为超级管理员,超级管理员不需要过滤资源/数据权限
     *
     * @return
     */
    @Override
    public boolean isSuperAdministrator() {
        Account principal = getPrincipal();
        if (principal != null) {
            return projectConfig.getDefaultSuperAdministratorAccountIds().contains(principal.getId());
        }
        return false;
    }
}

